<?php

/**
 * 73YC 购物流程
 * ============================================================================
 * * 版权所有 20013-* 梅州络客网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.alork.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: liubo $
 * $Id: index.php 17217 2013-10-19 06:29:08Z liubo $
*/
define('IN_ECS', true);

require(dirname(__FILE__) . '/includes/init.php');
require(ROOT_PATH . 'includes/lib_order.php');
require_once(ROOT_PATH . 'includes/classOrder.php');
/* 载入语言文件 */
require_once(ROOT_PATH . 'languages/' .$_CFG['lang']. '/user.php');
require_once(ROOT_PATH . 'languages/' .$_CFG['lang']. '/shopping_flow.php');

/*------------------------------------------------------ */
//-- AJAX计算结算金额
/*------------------------------------------------------ */
if ($_REQUEST['step'] == 'select_coupon')
{
    require(ROOT_PATH . 'includes/cls_json.php');
    $json   = new JSON;
    $postOrder = !empty($_POST['order'])?$_POST['order']:'';//AJAX提交过来的订单信息
    /* 实例化订单操作类 */
    $cOrder = new classOrder;
    $return = array('error' => '0', 'message' => '', 'content' => 0);
    $address_id = !empty($postOrder['AddressId'])?$postOrder['AddressId']:"";//获取配送地址ID
    if(!empty($address_id)){
        $cOrder->getUserAddrList($address_id);
        $consignee = $cOrder->consignee;
    }
    else{
        $consignee = !empty($_REQUEST['consignee'])?$_REQUEST['consignee']:$_SESSION['consignee'];
    }
    /* 是否正常结算 */
    $rid =!empty($postOrder['Rid'])?$postOrder['Rid']:"";
    if (!empty($rid)) {
        $key = md5($rid);
        $rec_id = $_SESSION[$key];
    } else {



        die('结算数据出错！');
    }

    /* 对商品信息赋值 */
    //获取订单商品
    $cart_goods = $cOrder->getCartGoods($rec_id);

    if (empty($cart_goods))
    {   
        $return['error'] = "605";
        $return['message'] = "商品获取信息错误";
        echo $json->encode($result);
        exit;
    }
    else
    {

        /* 计算订单的费用 */
        $cOrder->orderInfo['pay_id']=$postOrder['PayId'];
        if (!empty($postOrder['CouponId'])) {
            $cOrder->coupon_id=implode(',',$postOrder['CouponId']);
        }
        $total = $cOrder->getTotal();
        $return['content'] = $total;
    }
    echo $json->encode($return);
    exit;
}







/*------------------------------------------------------ */
//-- INPUT
/*------------------------------------------------------ */
if (empty($_REQUEST['step']))
{
    $_REQUEST['step'] = "cart";
}
/*------------------------------------------------------ */
//-- PROCESSOR
/*------------------------------------------------------ */
assign_template();
assign_dynamic('flow');
$position = assign_ur_here(0, $_LANG['shopping_flow']);
$smarty->assign('page_title',       $position['title']);    // 页面标题
$smarty->assign('top_title',$_LANG[$_REQUEST['step']] );    //顶端标题
$smarty->assign('lang',             $_LANG); // 语言
$smarty->assign('data_dir',    DATA_DIR);       // 数据目录
// 判断STEP参数是否在允许范围内
$is_stpe=array('addToCart','award','change_award', 'complete', 'update_cart' ,'add_to_cart_pigment','checkout','select_shipping','select_payment','change_integral','change_bonus','check_integral','done','done2','ajax_get_msg','ajax_get_price','ajax_update_cart','drop_goods','clear','validate_bonus','order_join','follow_cart','cart', 'deal_session');
if (!in_array($_REQUEST['step'], $is_stpe))
{
ecs_header("Location: index.php\n");
exit();
}

/*------------------------------------------------------ */
//-- 添加商品到购物车
/*------------------------------------------------------ */
if ($_REQUEST['step'] == 'addToCart')
{
    include_once(ROOT_PATH . 'includes/cls_json.php');
    $result = array('error' => 0, 'message' => '', 'content' => '', 'goods_id' => '');
    $json  = new JSON;
    /* 格式化参数 */
    $_REQUEST['id'] = array_filter(explode('-', $_REQUEST['id']));
    $_REQUEST['ext'] = !empty($_REQUEST['ext'])?array_filter(explode('-', $_REQUEST['ext'])):'';
    $_REQUEST['attr'] = !empty($_REQUEST['attr'])?array_filter(explode('-', $_REQUEST['attr'])):'';
    $_REQUEST['number'] = !empty($_REQUEST['number'])?array_filter(explode('-', $_REQUEST['number'])):'';
    if (is_array($_REQUEST['id'])) {
        /* 存在购物信息 */
        foreach ($_REQUEST['id'] as $key => $value) {
            /* 格式化参数为商品数据 */
            $goodsList[$key]['id'] = $value;
            $goodsList[$key]['extension_code'] = !empty($_REQUEST['ext'][$key])?$_REQUEST['ext'][$key]:'';
            $goodsList[$key]['goods_attr_id'] = !empty($_REQUEST['attr'][$key])?array_filter(explode(',', $_REQUEST['attr'][$key])):'';
            $goodsList[$key]['goods_number'] =!empty($_REQUEST['number'][$key])?$_REQUEST['number'][$key]:1;
        }
        /* 实例化前端订单类 */
        $cOrder = new classOrder;
        /* 执行添加购物车操作 */
        $result = $cOrder->addToCart($goodsList);
        if ($result['error'] == 0 && empty($_REQUEST['ext'])) {
            /* 普通商品加入购物车 */
            $cart_info = insert_cart_info();
            $result['number'] = $cart_info[0];
            $result['content'] = "<span>购物车一共$cart_info[0]件商品，共计$cart_info[1]</span>";
        }
        die($json->encode($result));
    } else {
        /* 不存在购物信息，参数出错 */
        $result['error'] = 1;
        $result['message'] = '参数错误，请联系客服！';
        die($json->encode($result));
    }
}

/*------------------------------------------------------ */
//-- 订单确认
/*------------------------------------------------------ */
elseif ($_REQUEST['step'] == 'checkout')
{
    // 判断是否恶意操作
    $rid = !empty($_REQUEST['rid']) ? $_REQUEST['rid'] : 0;
    $rec_id = isset($_REQUEST['rec_id']) ? $_REQUEST['rec_id'] : 0;                     //获取前台传来的勾选商品id
    // 是否有传勾选值
    if (empty($rec_id) && empty($rid)) {
        ecs_header("Location: flow.php\n");     //跳转到购物车页面
        exit();
    }
    // 是否有勾选
    if (!empty($rec_id) && empty($rid)) {
        $rid = rand(100000000, 999999999);
        $key = md5($rid);
        $_SESSION[$key] = $rec_id;
        ecs_header("Location: flow.php?step=checkout&rid={$rid}");
        exit();
    }
    // 勾选是否有值
    if (empty($rid) || empty($_SESSION[md5($rid)])) {
        ecs_header("Location: flow.php\n");     //跳转到购物车页面
        exit();
    } else {
        $rec_id = $_SESSION[md5($rid)];
        $smarty->assign('rid',              $_REQUEST['rid']);
    }

    /* 检查用户是否已经登录 */
    if (empty($_SESSION['user_id']))
    {
        /* 用户没有登录且没有选定匿名购物，转向到登录页面 */
        ecs_header("Location: user.php\n");
        exit;
    }

    /* 实例化订单操作类 */
    $cOrder  = new classOrder;
    $cOrder->time = $_CFG['systemTime'];
    // 获取订单商品
    $cart_goods = $cOrder->getCartGoods($rec_id);



    // dump($cart_goods);

    if (empty($cart_goods)) {
        header('Location:flow.php');
        exit;
    }
    $smarty->assign('goods_list', $cart_goods);

    // 获取用户收货地址列表
    $consignee_list = $cOrder->getUserAddrList();
    // 获取默认收货地址
    $consignee = $cOrder->consignee;
    $smarty->assign('consignee', $consignee);
    $smarty->assign('total', $cOrder->getTotal()); // 费用及统计信息

    //取得支付方式
    $pay_id = !empty($_SESSION['pay_id']) ? $_SESSION['pay_id'] : 1;
    $payment = payment_info($pay_id);

    /* 取得订单信息 */
    $order = $cOrder->orderInfo;
    // 选择的支付方式默认为支付宝
    $cOrder->orderInfo['pay_id'] = $order['pay_id'] = $payment['pay_id'];

    /* 计算订单的费用及统计信息 */
    $total = $cOrder->getTotal();

    /*判断是否有赠品*/
    $is_gift_start = $_CFG['is_gift_start'];
    /*获取优惠卷信息*/
    $coupon = $cOrder->getCoupon($total['amount']);

    /*获取优惠金额*/
    foreach ($coupon as $key => $value) {
        if ($value['is_free']) {
            $coupon[$key]['discount']=$total['shipping_fee']-$cOrder->getShippingFee($total['goods_price'], $cOrder->orderInfo['pay_id'], $cOrder->consignee, $total['goods_weight'],$total['is_shipping'],$value['is_free']);
        }
        if ($value['discount']>0) {
            $coupon[$key]['discount'] = $total['goods_price']*(1-$value['discount']);
        }

    }

    $smarty->assign('coupon', $coupon);           //优惠卷列表

    if ( $is_gift_start == 1) {
          /*查询赠品*/
            $gift_list = $cOrder->getGift($total['amount']);
            $is_gift = 0;//是否赠送完
            if (!empty($gift_list)) {
                                     $is_gift = 1;
                   foreach ($gift_list as $key => $value) {
                        $gift_lists[$value['parent_id']] = $value;
                        if ($value['min_price']==100) {
                            $gift_lists[$value['parent_id']]['rank'] = 1;
                        }
                        if ($value['min_price']==300) {
                            $gift_lists[$value['parent_id']]['rank'] = 2;
                        }
                        if ($value['min_price']==500) {
                            $gift_lists[$value['parent_id']]['rank'] = 3;
                        }
                        if($value['stock']>0){
                            $is_gift = 2;
                        }
                    }
                    if ($total['amount']>100) {
                        $rank =1;
                        $gift_lists[59]['name']="波普透明笔盒<br>波普铅笔6B(盒)<br>马利8k素描纸";
                        $gift_lists[60]['name']="马可铅笔7b<br>日钢美工小刀<br>雪山4k素描纸<br>樱花小橡皮";
                        $gift_lists[61]['name']="美文纸<br>雪山8k素描纸<br>雪山4k素描纸<br>";
                        $gift_lists[62]['name']="凤凰纸擦笔三支<br>透明胶带<br>日钢美工小刀<br>波普铅笔8B<br>雪山8k素描纸";
                        $gift_lists[63]['name']="凤凰纸擦笔大号<br>辉柏嘉可塑橡皮<br>波普铅笔8B<br>雪山4k素描纸";
                    }
                    if ($total['amount']>300) {
                        $rank =2;
                        $gift_lists[64]['name']="毕加猪鬃毛画笔<br>温莎油画12色<br>马利画稀释剂<br>马利·猪鬃笔刷<br>凤凰纯棉油画框";
                        $gift_lists[65]['name']="辉柏嘉可塑橡皮<br>樱花小橡皮<br>康颂4k素描纸<br>雪山素描本<br>波普铅笔6B-盒<br>马可铅笔9B-盒<br>波普速写纸100张";
                        $gift_lists[66]['name']="温莎水彩12色<br>毕加索狼毫画笔<br>梅花调色盘<br>雪山4k水彩纸";
                        $gift_lists[67]['name']="波普4k素描纸<br>辉柏嘉48色彩铅";
                        $gift_lists[68]['name']="波普42格颜料盒<br>波普4k素描纸<br>波普鱼尾画笔";
                        $gift_lists[69]['name']="马利水彩24色<br>方舟电动橡皮<br>方舟颜料盒";
                        $gift_lists[70]['name']="木质调色板圆形<br>温莎油画18色<br>波普鱼尾画笔";
                    }
                    if ($total['amount']>500) {
                        $rank =3;
                        $gift_lists[71]['name']="马利水彩24色<br>波普鱼尾画笔<br>美纹纸<br>波普高级4k素描<br>雪山4k水彩纸<br>马利4k画板<br>波普鱼尾画笔";
                        $gift_lists[72]['name']="马可铅笔2b<br>工具箱16寸<br>索普大手摇画架<br>雪山4k素描纸<br>马利4k画板<br>雪山素描本";
                        $gift_lists[73]['name']="马可48色彩铅<br>雪山素描本<br>马利色粉12色<br>毕加索勾线笔3支<br>梅花透明调色盘<br>   凤凰油画12色";
                        $gift_lists[74]['name']="辉柏嘉彩铅24色<br>雪山素描本<br>马利色粉12色<br>康颂8k水彩本<br>毕加索勾线笔3支<br>樱花小橡皮擦";
                    }


                    $smarty->assign('is_gift', $is_gift); // 是否赠送完
                    $smarty->assign('rank', $rank); // 订单信息

                    if ($is_gift == 2) {
                    $smarty->assign('gift_list', $gift_lists); // 赠品信息
                    }
            }
            if ($is_gift == 0) {
                    $nex_price = (100-$total['amount']);
                    $smarty->assign('nex_price', $nex_price); // 赠品信息
            }
    }

    $smarty->assign('is_gift_start', $is_gift_start); // 赠品活动是否开始
    $smarty->assign('order', $order); // 订单信息
    $smarty->assign('config', $_CFG);/* 取得购物流程设置 */
    $smarty->assign('total', $total); // 费用及统计信息
    $smarty->assign('payment', $payment); // 支付方式
    $area_id = is_buy($consignee);
    $smarty->assign('area_id',            $area_id);
    $smarty->assign('gift_goods',            $gift_goods);
    $smarty->assign('step',            $_REQUEST['step']);
    $smarty->display("confirm_order.dwt");
    exit;
}
elseif ($_REQUEST['step'] == 'select_payment')
{

    /*------------------------------------------------------ */
    //-- 判断是否恶意操作
    /*------------------------------------------------------ */
    $rid = !empty($_REQUEST['rid']) ? $_REQUEST['rid'] : 0;
    // 勾选是否有值
    if (empty($rid) || empty($_SESSION[md5($rid)])) {
        ecs_header("Location: flow.php\n");     //跳转到购物车页面
        exit();
    } else {
        $rec_id = $_SESSION[md5($rid)];
        $smarty->assign('rid',              $_REQUEST['rid']);
    }

    // /*------------------------------------------------------ */
    // //-- 改变支付方式
    // /*------------------------------------------------------ */
    include_once('includes/cls_json.php');
    $json = new JSON;
    $smarty->assign('step',            $_REQUEST['step']);

    if ($_REQUEST['pay_id']) {
        $_SESSION['pay_id'] = $_REQUEST['pay_id'];
        $url = "flow.php?step=checkout&rid=$rid";
        echo $json->encode($url);
        exit();
    }
    /* 实例化订单操作类 */
    $cOrder  = new classOrder;
    // 获取用户收货地址列表
    $consignee_list = $cOrder->getUserAddrList();
    // 获取默认收货地址
    $consignee = $cOrder->consignee;

    $payment_list = available_payment_list(is_cod($consignee), $cod_fee);
    $pay_id = !empty($_SESSION['pay_id']) ? $_SESSION['pay_id'] : 1;
    $smarty->assign('pay_id',            $pay_id);
    $smarty->assign('payment_list',            $payment_list);
    $smarty->display('confirm_order.dwt');
    exit;
}

/*------------------------------------------------------ */
//-- 完成购物车订单操作，提交到数据库
//-- AJAX处理
/*------------------------------------------------------ */
elseif ($_REQUEST['step'] == 'done')
{

    /*------------------------------------------------------ */
    //-- 判断是否恶意操作
    /*------------------------------------------------------ */
    $rid = !empty($_REQUEST['rid']) ? $_REQUEST['rid'] : 0;
    // 勾选是否有值
    if (empty($rid) || empty($_SESSION[md5($rid)])) {

    } else {
        $rec_id = $_SESSION[md5($rid)];
    }
    include_once(ROOT_PATH . 'includes/lib_clips.php');
    include_once(ROOT_PATH . 'includes/lib_payment.php');
    include_once(ROOT_PATH . 'includes/classCounter.php');
    include_once(ROOT_PATH . 'includes/cls_json.php');
    include_once(ROOT_PATH . 'includes/classLock.php');


    /* 实例化订单操作类 */
    $cOrder = new classOrder;
    $json   = new JSON;
    $lock   = new classLock;
    /*初始化返回信息*/
    $return = array('error' => 0,'message' => '','content' => '' );
    /*判断用户是否登录*/
    if (empty($_SESSION['user_id'])) {
        $return['error']   = 600;
        $return['message'] = '请登录后再操作';
        $return['content'] = '';
        echo $json->encode($return);
        exit;
    }
    $lock->lock($_SESSION['user_id']);
    /*获取订单信息*/
    $postOrder = !empty($_POST['order'])?$_POST['order']:'';//AJAX提交过来的数据
    if (empty($postOrder)) {
        $return['error']   = 401;
        $return['message'] = '订单信息为空';
        $return['content'] = '';
        echo $json->encode($return);
        exit;
    }
    /*检查是否有选择商品*/
    $rid =!empty($postOrder['Rid'])?$postOrder['Rid']:"";
    if (!empty($rid)) {
        $key = md5($rid);
        $recId = $_SESSION[$key];
    }
    if (empty($recId)) {
        $return['error']   = 605;
        $return['message'] = '商品获取信息错误';
        $return['content'] = '';
        echo $json->encode($return);
        exit;
    }
    /* 检查勾选商品是否存在 */
    $cartGoods = $cOrder->getCartGoods($recId);
    if (empty($cartGoods)) {
        $return['error']   = 605;
        $return['message'] = '结算商品不存在';
        $return['content'] = '';
        echo $json->encode($return);
        exit;
    }
    /*检查地址是否为空*/
    $addressId = !empty($postOrder['AddressId'])?intval($postOrder['AddressId']):"";

    /*检查是否有配送地址*/
    if (!empty($addressId)) {
        /*获取地址信息*/
        $cOrder->getUserAddrList($addressId);
        $consignee = $cOrder->consignee;
        if (empty($consignee)) {
            $return['error']   = 603;
            $return['message'] = '获取地址信息错误';
            $return['content'] = '';
            echo $json->encode($return);
            exit;
        }
    } else {
        $return['error']   = 603;
        $return['message'] = '地址信息错误';
        $return['content'] = '';
        echo $json->encode($return);
        exit;
    }
    $payId = !empty($postOrder['PayId'])?intval($postOrder['PayId']):"";
    // 检查是否有选择支付方式
    if (empty($payId)) {
        $return['error']   = 604;
        $return['message'] = '没有选择支付方式';
        $return['content'] = '';
        echo $json->encode($return);
        exit;
    }
    /* 支付方式 */
    if ($payId > 0)
    {
        $payment = payment_info($payId);
        if($payment['pay_name']){
            $order['pay_name'] = addslashes($payment['pay_name']);
        }else{
            $return['error']   = 604;
            $return['message'] = '支付方式不存在';
            $return['content'] = '';
            echo $json->encode($return);
            exit;
        }
    }
        /* 实例化订数器操作类 */
    $c = new classCounter;
        /* 尝试添加计数器 */
    $c->addCounter('orderSum');
    /* 计数器加1 */
    $runSum = $c->inCounter('orderSum');
    // if (!empty($runSum) && $runSum >= $_CFG['orderMaxNum']) {
    //     $return['error']   = 610;
    //     $return['message'] = '服务器繁忙请稍后再试';
    //     $return['content'] = '';
    //     goto result;
    // }
    /* 执行过程 */
    /*重组商品筛选活动商品*/
    foreach ($cartGoods as $key => $value) {
        if ($value['extension_code'] == 'limit' || $value['extension_code'] == 'libao' || $value['extension_code'] == 'gift' || $value['extension_code'] == 'buyone') {
            # code...
        }
        else{
            $cartGoodsCommon[$key] = $value;
        }
    }
    /*预减库存库存不足返回错误*/
    if (!empty($cartGoodsCommon)) {
        $run = $GLOBALS['virtualStock']->outStockList($cartGoodsCommon);
        if (!$run) {
            $return['error']   = 602;
            $return['message'] = '库存不足是否返回购物车操作';
            $return['content'] = '';
            goto result;
        }
    }
    /*运行业务*/
    $user_id = $_SESSION['user_id'];
    /*初始订单基本信息*/
    $order = array(
        'shipping_id'     => 13,
        'shipping_name'   => '速递',
        'pay_id'          => $payId,
        'pay_name'        => addslashes($payment['pay_name']),
        'postscript'      => trim($postOrder['Message']),
        'user_id'         => $_SESSION['user_id'],
        'add_time'        => gmtime(),
        'order_status'    => OS_UNCONFIRMED,
        'shipping_status' => SS_UNSHIPPED,
        'pay_status'      => PS_UNPAYED,
        'country'         => $consignee['country'],
        'province'        => $consignee['province'],
        'city'            => $consignee['city'],
        'district'        => $consignee['district'],
        'area_id'         => $consignee['area_id'],
        'consignee'       => $consignee['consignee'],
        'address'         => $consignee['address'],
        'mobile'          => $consignee['mobile'],
        'from_ad'         => '4',
        'referer'         => '手机下单',
        'agency_id'       => 3,
        );
    if (!empty($postOrder['CouponId'])) {
        $order['coupon_id'] = implode(',',$postOrder['CouponId']);
        $cOrder->coupon_id  = $order['coupon_id'];
    }
    /* 订单中的总额 */
    $cOrder->orderInfo = $order;
    $total = $cOrder->getTotal();
    $order['discount'] = $total['discount'];
    $order['is_free'] = $total['is_free'];
    $order['goods_amount'] = $total['goods_price'];
    $order['shipping_fee'] = $total['shipping_fee']; // 配送费用
    $order['pay_fee']      = $total['pay_fee'];
    $order['cod_fee']      = $total['cod_fee'];
    $order['order_amount'] = number_format($total['amount'], 2, '.', '');
    /* 如果订单金额为0（使用余额或积分或红包支付），修改订单状态为已确认、已付款 */
    if ($order['order_amount'] <= 0)
    {
        $order['order_status'] = OS_CONFIRMED;
        $order['confirm_time'] = gmtime();
        $order['pay_status']   = PS_PAYED;
        $order['pay_time']     = gmtime();
        $order['order_amount'] = 0;
    }
    /* 更新订单信息 */
    $cOrder->orderInfo = $order;
    /*使用优惠卷*/
    if (!empty($order['coupon_id'])) {
        $cOrder->useCoupon($order['coupon_id']);//标记优惠卷为已使用
    }
    /* 处理赠品信息 */
    if (!empty($cOrder->orderInfo) && !empty($postOrder['gift'])) {
        if (!$lock->lock(md5('gift' . $postOrder['gift']))) {
            $result['error']   = 901;
            $result['message'] = '赠品处理出错，请稍候再提交！';
            $result['content'] = '';
            goto result;
        }
        $sql = 'SELECT min_price, parent_id, original_price, name FROM ' . $ecs->table('activity') . ' WHERE parent_id = ' . intval($postOrder['gift']);
        $giftInfo = $db->getRow($sql);
        if (!empty($giftInfo) && $order['order_amount'] >= $giftInfo['min_price']) {
            // 查询赠品数量
            $sql = 'SELECT valid_number FROM ' . $ecs->table('activity_stock') . ' WHERE parent_id = ' . intval($postOrder['gift']);
            $giftInfo['valid_number'] = $db->getOne($sql);
            if (!empty($giftInfo['valid_number'])) {
                // 如果存在可用数量则加入订单商品信息
                $cOrder->goodsList[] = array(
                    'goods_id'       => '0',
                    'goods_thumb'    => '',
                    'goods_name'     => $giftInfo['name'],
                    'goods_sku'      => 0,
                    'goods_number'   => 1,
                    'market_price'   => $giftInfo['original_price'],
                    'goods_price'    => 0,
                    'goods_attr'     => '',
                    'goods_attr_sku' => 0,
                    'is_real'        => 1,
                    'extension_code' => 'gift',
                    'parent_id'      => $giftInfo['parent_id'],
                    'is_gift'        => 1,
                    'goods_attr_id'  => 0,
                    'compose_note'   => '',
                    );
                $sql = 'UPDATE ' . $ecs->table('activity_stock') . ' SET valid_number = valid_number - 1 WHERE parent_id = ' . $giftInfo['parent_id'];
                $db->query($sql);
            }
        }
        $lock->unlock(md5('gift' . $postOrder['gift']));
    }
    /* 提交订单 */
    $return = $cOrder->orderDone();
    if ($result !== false) {
        goto result;
    } else {
        $result['error']   = 610;
        $result['message'] = '服务器出错请联系客服处理！';
        $result['content'] = '';
        goto result;
    }
    /* 返回json状态及信息 */
    result:
    $lock->unlock($_SESSION['user_id']);
    /* 计数器减1 */
    $c->deCounter('orderSum');
    echo $json->encode($return);
    exit;
}

/*------------------------------------------------------ */
//-- 订单完成页面
/*------------------------------------------------------ */

elseif ($_REQUEST['step'] == 'complete'){
    include_once(ROOT_PATH . 'mobile/includes/lib_transaction.php');
    include_once(ROOT_PATH . 'mobile/includes/lib_payment.php');
    include_once(ROOT_PATH . 'mobile/includes/lib_clips.php');

    $order_id = !empty($_REQUEST['order_id']) ? $_REQUEST['order_id'] :'';
    $user_id  = !empty($_SESSION['user_id'])  ? $_SESSION['user_id']  :'';
    $smarty->assign('top_title', '完成订单');
    //判断是否有USER_ID根订单号
    if(empty($order_id)||empty($user_id)){
       header('location:index.html');
    }
    $order = get_order_detail($order_id, $user_id);
    $smarty->assign('order',            $order);
    $smarty->assign('back_url',   'user.php?act=order_list');
}

/*------------------------------------------------------ */
//-- 删除购物车中的商品
/*------------------------------------------------------ */

elseif ($_REQUEST['step'] == 'drop_goods')
{
    if($_REQUEST['mode']=='all'){
        $rec_id = array_filter(explode('-',$_GET['id']));
        $cOrder = new classOrder;
        $cOrder->delCartGoods($rec_id);
        ecs_header("Location: flow.php\n");
        exit;
    }else{
        $rec_id = intval($_GET['id']);
        $cOrder = new classOrder;
        $cOrder->delCartGoods($rec_id);
        ecs_header("Location: flow.php\n");
        exit;
    }
}

/*------------------------------------------------------ */
//-- AJAX获取购物车中所有商品的总价
/*------------------------------------------------------ */

// elseif($_REQUEST['step'] == 'ajax_get_price')
// {
//     require(ROOT_PATH . 'includes/cls_json.php');
//     $json = new JSON;

//     //查询购物车的中所有商品的数量，价格
//     $sql = "SELECT goods_number, goods_price FROM " . $GLOBALS['ecs']->table('cart') .
//         " WHERE user_id = " . $_REQUEST['user_id'];
//     $goods = $GLOBALS['db']->getAll($sql);

//     echo $json->encode($goods);
//     exit;
// }

/*------------------------------------------------------ */
//-- AJAX获取购物车中指定商品的数量
/*------------------------------------------------------ */

elseif($_REQUEST['step'] == 'ajax_get_msg')
{
    require(ROOT_PATH . 'includes/cls_json.php');
    $json = new JSON;

    //查询购物车的中勾选的商品的数量
    $sql = "SELECT goods_number, goods_price FROM " . $GLOBALS['ecs']->table('cart') .
        " WHERE rec_id = " . $_REQUEST['id'] . " AND user_id = " . $_REQUEST['user_id'];
    $goods = $GLOBALS['db']->getRow($sql);

    echo $json->encode($goods);
    exit;
}

/*------------------------------------------------------ */
//-- AJAX更新购物车
/*------------------------------------------------------ */

elseif ($_REQUEST['step'] == 'ajax_update_cart')
{
    require(ROOT_PATH . 'includes/cls_json.php');
    $json   = new JSON;
    if (isset($_REQUEST['goods_number']) && isset($_REQUEST['id']))
    {
        flow_update_cart(array($_REQUEST['id'] => $_REQUEST['goods_number']));
    }
    //查询更新过后的价格
    $rec_id = $_REQUEST['id'];
    $sql = "SELECT goods_price FROM ".$GLOBALS['ecs']->table('cart')." WHERE rec_id = $rec_id ";
    $goods_price = $GLOBALS['db']->getOne($sql);
    $result['error'] = 0;
    $result['content'] = $goods_price;
    echo $json->encode($result);
    exit;
}


// 购物车页面
elseif($_REQUEST['step'] == 'cart')
{
    /* 实例化订单类 */
    $cOrder = new classOrder;
    $cOrder->time = $_CFG['systemTime'];
    $smarty->assign('goods_list', $cOrder->getCartGoods());   //购物车商品列表
    $smarty->assign('flow' , "1");
    $state = 0;
    if (empty($_SESSION['cart_popup'])&&!empty($_SESSION['user_id'])) {
         $sql =  'SELECT ct.type_code FROM '.$ecs->table('coupon')."AS c ".
                " LEFT JOIN ".$ecs->table('coupon_type')."AS ct ON c.type_id = ct.type_id ".
                " WHERE c.user_id = '".$_SESSION['user_id']."' AND c.is_use = 0 ";
                $coupon = $db->getAll($sql);
        if (!empty($coupon)) {
          $state=2;
            foreach ($coupon as $key => $value) {
                if (!empty($value['type_code'])&&$value['type_code']=="discount") {
                    $state=3;
                }
            }
            $_SESSION['cart_popup'] =1;
        }
   }
    if ($_SESSION['user_id'] != 12 ) {
            $state =0;
    }
   $smarty->assign('state', $state);
}
$smarty->assign('user_id' , $_SESSION['user_id']);

$smarty->assign('is_gift_start', $_CFG['is_gift_start']);/*判断赠品活动是否开始*/
$smarty->assign('step',            $_REQUEST['step']);
assign_dynamic('shopping_flow');
$smarty->display('flow.dwt');


/*------------------------------------------------------ */
//-- PRIVATE FUNCTION
/*------------------------------------------------------ */

/**
 * 获得用户的可用积分
 *
 * @access  private
 * @return  integral
 */
function flow_available_points()
{
    $sql = "SELECT SUM(g.integral * c.goods_number) ".
            "FROM " . $GLOBALS['ecs']->table('cart') . " AS c, " . $GLOBALS['ecs']->table('goods') . " AS g " .
            "WHERE c.session_id = '" . SESS_ID . "' AND c.goods_id = g.goods_id AND c.is_gift = 0 AND g.integral > 0 " .
            "AND c.rec_type = '" . CART_GENERAL_GOODS . "'";

    $val = intval($GLOBALS['db']->getOne($sql));

    return integral_of_value($val);
}

/**
 * 更新购物车中的商品数量
 *
 * @access  public
 * @param   array   $arr
 * @return  void
 */
function flow_update_cart($arr)
{
    /* 处理 */
    foreach ($arr AS $key => $val)
    {
        $val = intval(make_semiangle($val));
        if ($val <= 0 || !is_numeric($key))
        {
            continue;
        }

        //查询：
        $sql = "SELECT gs.goods_number AS goods_stock, c.goods_id, c.goods_attr_id, c.product_id, c.extension_code FROM " .$GLOBALS['ecs']->table('cart').
               " c LEFT JOIN " . $GLOBALS['ecs']->table('goods_stock') . " gs ON(gs.goods_id = c.goods_id AND gs.goods_attr_id = c.goods_attr_id AND gs.area_id = c.area_id) ".
               " WHERE c.rec_id='$key' AND c.user_id = '{$_SESSION['user_id']}'";
        $goods = $GLOBALS['db']->getRow($sql);

        //订货数量大于0
        if ($val > 0)
        {
            if($val <= $goods['goods_stock'])
            {
                $attr_id    = empty($goods['goods_attr_id']) ? array() : explode(',', $goods['goods_attr_id']);
                $goods_price = get_final_price($goods['goods_id'], $val, true, $attr_id);

                //更新购物车中的商品数量
                if($goods_price){
                    $sql = "UPDATE " .$GLOBALS['ecs']->table('cart').
                            " SET goods_number = '$val', goods_price = '$goods_price' WHERE rec_id='$key' AND user_id = '{$_SESSION['user_id']}'";
                }else{
                    $sql = "UPDATE " .$GLOBALS['ecs']->table('cart').
                            " SET goods_number = '$val' WHERE rec_id='$key' AND user_id = '{$_SESSION['user_id']}'";
                }
            }
        }
        //订货数量等于0
        else
        {
            $sql = "DELETE FROM " .$GLOBALS['ecs']->table('cart').
                " WHERE rec_id='$key' AND user_id = '{$_SESSION['user_id']}'";
        }

        $GLOBALS['db']->query($sql);
    }

    /* 删除所有赠品 */
    // $sql = "DELETE FROM " . $GLOBALS['ecs']->table('cart') . " WHERE session_id = '" .SESS_ID. "' AND is_gift <> 0";
    $GLOBALS['db']->query($sql);
}

/**
 * 检查订单中商品库存
 *
 * @access  public
 * @param   array   $arr
 *
 * @return  void
 */
function flow_cart_stock($arr)
{
    foreach ($arr AS $key => $val)
    {
        $val = intval(make_semiangle($val));
        if ($val <= 0 || !is_numeric($key))
        {
            continue;
        }

        $sql = "SELECT `goods_id`, `goods_attr_id`, `extension_code` FROM" .$GLOBALS['ecs']->table('cart').
               " WHERE rec_id='$key' AND session_id='" . SESS_ID . "'";
        $goods = $GLOBALS['db']->getRow($sql);

        $sql = "SELECT g.goods_name, g.goods_number, c.product_id ".
                "FROM " .$GLOBALS['ecs']->table('goods'). " AS g, ".
                    $GLOBALS['ecs']->table('cart'). " AS c ".
                "WHERE g.goods_id = c.goods_id AND c.rec_id = '$key'";
        $row = $GLOBALS['db']->getRow($sql);

        //系统启用了库存，检查输入的商品数量是否有效
        if (intval($GLOBALS['_CFG']['use_storage']) > 0 && $goods['extension_code'] != 'package_buy')
        {
            if ($row['goods_number'] < $val)
            {
                show_message(sprintf($GLOBALS['_LANG']['stock_insufficiency'], $row['goods_name'],
                $row['goods_number'], $row['goods_number']));
                exit;
            }

            /* 是货品 */
            $row['product_id'] = trim($row['product_id']);
            if (!empty($row['product_id']))
            {
                $sql = "SELECT product_number FROM " .$GLOBALS['ecs']->table('products'). " WHERE goods_id = '" . $goods['goods_id'] . "' AND product_id = '" . $row['product_id'] . "'";
                $product_number = $GLOBALS['db']->getOne($sql);
                if ($product_number < $val)
                {
                    show_message(sprintf($GLOBALS['_LANG']['stock_insufficiency'], $row['goods_name'],
                    $row['goods_number'], $row['goods_number']));
                    exit;
                }
            }
        }
        elseif (intval($GLOBALS['_CFG']['use_storage']) > 0 && $goods['extension_code'] == 'package_buy')
        {
            if (judge_package_stock($goods['goods_id'], $val))
            {
                show_message($GLOBALS['_LANG']['package_stock_insufficiency']);
                exit;
            }
        }
    }

}

/**
 * 删除购物车中的商品
 *
 * @access  public
 * @param   integer $id
 * @return  void
 */
function flow_drop_cart_goods($id)
{
    $sql = "DELETE FROM " . $GLOBALS['ecs']->table('cart') .
                    " WHERE (session_id = '" . SESS_ID . "' OR user_id = $_SESSION[user_id]) " .
                    "AND rec_id = '$id' LIMIT 1";
    $GLOBALS['db']->query($sql);
    flow_clear_cart_alone();
}

/**
 * 删除购物车中不能单独销售的商品
 *
 * @access  public
 * @return  void
 */
function flow_clear_cart_alone()
{
    /* 查询：购物车中所有不可以单独销售的配件 */
    $sql = "SELECT c.rec_id, gg.parent_id
            FROM " . $GLOBALS['ecs']->table('cart') . " AS c
                LEFT JOIN " . $GLOBALS['ecs']->table('group_goods') . " AS gg ON c.goods_id = gg.goods_id
                LEFT JOIN" . $GLOBALS['ecs']->table('goods') . " AS g ON c.goods_id = g.goods_id
            WHERE c.session_id = '" . SESS_ID . "'
            AND c.extension_code <> 'package_buy'
            AND gg.parent_id > 0
            AND g.is_alone_sale = 0";
    $res = $GLOBALS['db']->query($sql);
    $rec_id = array();
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $rec_id[$row['rec_id']][] = $row['parent_id'];
    }

    if (empty($rec_id))
    {
        return;
    }

    /* 查询：购物车中所有商品 */
    $sql = "SELECT DISTINCT goods_id
            FROM " . $GLOBALS['ecs']->table('cart') . "
            WHERE session_id = '" . SESS_ID . "'
            AND extension_code <> 'package_buy'";
    $res = $GLOBALS['db']->query($sql);
    $cart_good = array();
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $cart_good[] = $row['goods_id'];
    }

    if (empty($cart_good))
    {
        return;
    }

    /* 如果购物车中不可以单独销售配件的基本件不存在则删除该配件 */
    $del_rec_id = '';
    foreach ($rec_id as $key => $value)
    {
        foreach ($value as $v)
        {
            if (in_array($v, $cart_good))
            {
                continue 2;
            }
        }

        $del_rec_id = $key . ',';
    }
    $del_rec_id = trim($del_rec_id, ',');

    if ($del_rec_id == '')
    {
        return;
    }

    /* 删除 */
    $sql = "DELETE FROM " . $GLOBALS['ecs']->table('cart') ."
            WHERE session_id = '" . SESS_ID . "'
            AND rec_id IN ($del_rec_id)";
    $GLOBALS['db']->query($sql);
}

/**
 * 比较优惠活动的函数，用于排序（把可用的排在前面）
 * @param   array   $a      优惠活动a
 * @param   array   $b      优惠活动b
 * @return  int     相等返回0，小于返回-1，大于返回1
 */
function cmp_favourable($a, $b)
{
    if ($a['available'] == $b['available'])
    {
        if ($a['sort_order'] == $b['sort_order'])
        {
            return 0;
        }
        else
        {
            return $a['sort_order'] < $b['sort_order'] ? -1 : 1;
        }
    }
    else
    {
        return $a['available'] ? -1 : 1;
    }
}



/**
 * 根据购物车判断是否可以享受某优惠活动
 * @param   array   $favourable     优惠活动信息
 * @return  bool
 */
function favourable_available($favourable)
{
    /* 会员等级是否符合 */
    $user_rank = $_SESSION['user_rank'];
    if (strpos(',' . $favourable['user_rank'] . ',', ',' . $user_rank . ',') === false)
    {
        return false;
    }

    /* 优惠范围内的商品总额 */
    $amount = cart_favourable_amount($favourable);

    /* 金额上限为0表示没有上限 */
    return $amount >= $favourable['min_amount'] &&
        ($amount <= $favourable['max_amount'] || $favourable['max_amount'] == 0);
}

/**
 * 取得优惠范围描述
 * @param   array   $favourable     优惠活动
 * @return  string
 */
function act_range_desc($favourable)
{
    if ($favourable['act_range'] == FAR_BRAND)
    {
        $sql = "SELECT brand_name FROM " . $GLOBALS['ecs']->table('brand') .
                " WHERE brand_id " . db_create_in($favourable['act_range_ext']);
        return join(',', $GLOBALS['db']->getCol($sql));
    }
    elseif ($favourable['act_range'] == FAR_CATEGORY)
    {
        $sql = "SELECT cat_name FROM " . $GLOBALS['ecs']->table('category') .
                " WHERE cat_id " . db_create_in($favourable['act_range_ext']);
        return join(',', $GLOBALS['db']->getCol($sql));
    }
    elseif ($favourable['act_range'] == FAR_GOODS)
    {
        $sql = "SELECT goods_name FROM " . $GLOBALS['ecs']->table('goods') .
                " WHERE goods_id " . db_create_in($favourable['act_range_ext']);
        return join(',', $GLOBALS['db']->getCol($sql));
    }
    else
    {
        return '';
    }
}

/**
 * 取得购物车中已有的优惠活动及数量
 * @return  array
 */
function cart_favourable()
{
    $list = array();
    $sql = "SELECT is_gift, COUNT(*) AS num " .
            "FROM " . $GLOBALS['ecs']->table('cart') .
            " WHERE session_id = '" . SESS_ID . "'" .
            " AND rec_type = '" . CART_GENERAL_GOODS . "'" .
            " AND is_gift > 0" .
            " GROUP BY is_gift";
    $res = $GLOBALS['db']->query($sql);
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $list[$row['is_gift']] = $row['num'];
    }

    return $list;
}

/**
 * 购物车中是否已经有某优惠
 * @param   array   $favourable     优惠活动
 * @param   array   $cart_favourable购物车中已有的优惠活动及数量
 */
function favourable_used($favourable, $cart_favourable)
{
    if ($favourable['act_type'] == FAT_GOODS)
    {
        return isset($cart_favourable[$favourable['act_id']]) &&
            $cart_favourable[$favourable['act_id']] >= $favourable['act_type_ext'] &&
            $favourable['act_type_ext'] > 0;
    }
    else
    {
        return isset($cart_favourable[$favourable['act_id']]);
    }
}

/**
 * 添加优惠活动（赠品）到购物车
 * @param   int     $act_id     优惠活动id
 * @param   int     $id         赠品id
 * @param   float   $price      赠品价格
 */
function add_gift_to_cart($act_id, $id, $price)
{
    $sql = "INSERT INTO " . $GLOBALS['ecs']->table('cart') . " (" .
                "user_id, session_id, goods_id, goods_sn, goods_name, market_price, goods_price, ".
                "goods_number, is_real, extension_code, parent_id, is_gift, rec_type ) ".
            "SELECT '$_SESSION[user_id]', '" . SESS_ID . "', goods_id, goods_sn, goods_name, market_price, ".
                "'$price', 1, is_real, extension_code, 0, '$act_id', '" . CART_GENERAL_GOODS . "' " .
            "FROM " . $GLOBALS['ecs']->table('goods') .
            " WHERE goods_id = '$id'";
    $GLOBALS['db']->query($sql);
}

/**
 * 添加优惠活动（非赠品）到购物车
 * @param   int     $act_id     优惠活动id
 * @param   string  $act_name   优惠活动name
 * @param   float   $amount     优惠金额
 */
function add_favourable_to_cart($act_id, $act_name, $amount)
{
    $sql = "INSERT INTO " . $GLOBALS['ecs']->table('cart') . "(" .
                "user_id, session_id, goods_id, goods_sn, goods_name, market_price, goods_price, ".
                "goods_number, is_real, extension_code, parent_id, is_gift, rec_type ) ".
            "VALUES('$_SESSION[user_id]', '" . SESS_ID . "', 0, '', '$act_name', 0, ".
                "'" . (-1) * $amount . "', 1, 0, '', 0, '$act_id', '" . CART_GENERAL_GOODS . "')";
    $GLOBALS['db']->query($sql);
}

/**
 * 取得购物车中某优惠活动范围内的总金额
 * @param   array   $favourable     优惠活动
 * @return  float
 */
function cart_favourable_amount($favourable)
{
    /* 查询优惠范围内商品总额的sql */
    $sql = "SELECT SUM(c.goods_price * c.goods_number) " .
            "FROM " . $GLOBALS['ecs']->table('cart') . " AS c, " . $GLOBALS['ecs']->table('goods') . " AS g " .
            "WHERE c.goods_id = g.goods_id " .
            "AND c.session_id = '" . SESS_ID . "' " .
            "AND c.rec_type = '" . CART_GENERAL_GOODS . "' " .
            "AND c.is_gift = 0 " .
            "AND c.goods_id > 0 ";

    /* 根据优惠范围修正sql */
    if ($favourable['act_range'] == FAR_ALL)
    {
        // sql do not change
    }
    elseif ($favourable['act_range'] == FAR_CATEGORY)
    {
        /* 取得优惠范围分类的所有下级分类 */
        $id_list = array();
        $cat_list = explode(',', $favourable['act_range_ext']);
        foreach ($cat_list as $id)
        {
            $id_list = array_merge($id_list, array_keys(cat_list(intval($id), 0, false)));
        }

        $sql .= "AND g.cat_id " . db_create_in($id_list);
    }
    elseif ($favourable['act_range'] == FAR_BRAND)
    {
        $id_list = explode(',', $favourable['act_range_ext']);

        $sql .= "AND g.brand_id " . db_create_in($id_list);
    }
    else
    {
        $id_list = explode(',', $favourable['act_range_ext']);

        $sql .= "AND g.goods_id " . db_create_in($id_list);
    }

    /* 优惠范围内的商品总额 */
    return $GLOBALS['db']->getOne($sql);
}

?>
